﻿<template>
    <full-screen-dialog
        :title="titleMap[mode]"
        v-model="visible"
        :width="1300"
        destroy-on-close
        @closed="$emit('closed')"
    >
        <el-form :model="entityObj" :rules="rules" :disabled="mode == 'Show'" ref="dialogForm">
            <el-collapse class="title" style="margin-bottom:10px ;">
                <div class="collapse-header" @click="toggleCollapse">
                    <span>基础信息</span>
                    <div style="display: flex;align-items: center;">
                        <span class="expand-text">{{ isCollapsed ? '展开' : '收起' }}</span>
                        <img
                            v-if="isCollapsed"
                            class="icon-img"
                            src="https://oss.jtmckj.com/pc/images/pay/arrow-bt.png"
                        />
                        <img
                            v-else
                            class="icon-img"
                            src="https://oss.jtmckj.com/pc/images/pay/arrow-top.png"
                        />
                    </div>
                </div>
                <div v-show="!isCollapsed" class="collapse-content1">
                    <el-row>
                        <el-col :span="16">
                            <el-form-item label-width="120px" label="收货订单编号:">
                                <el-tooltip
                                    placement="top"
                                    v-for="(item,index) in entityObj.orderDetail"
                                    :key="item.purchaseOrderId"
                                >
                                    <template #content>
                                        要货单位: {{item.storeName}}
                                        <br />
                                        申请人:{{item.crName}}
                                        <br />
                                        申请时间:{{item.crDate}}
                                        <br />
                                        期望到货时间:{{item.expectedDate}}
                                        <br />
                                        收货状态:{{item.taskStatusDesc}}
                                    </template>
                                    <span
                                        style="color: blue;margin-right: 5px;"
                                    >{{item.orderCode}}{{ index !== entityObj.orderDetail.length - 1 ? ',' : '' }}</span>
                                </el-tooltip>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <!-- <el-row>
                <el-col :span="8">
                    <el-form-item label-width="155px" label="编号:">
                        {{ entityObj.orderCode }}
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="155px" label="要货单位:">
                        {{ entityObj.storeName }}
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="155px" label="申请人:">
                        {{ entityObj.crName }}
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label-width="155px" label="申请时间:">
                        {{ entityObj.crDate }}
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="155px" label="期望到货时间:">
                        {{ entityObj.expectedDate }}
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="155px" label="收货状态:">
                        {{ entityObj.taskStatusDesc }}
                    </el-form-item>
                </el-col>
                    </el-row>-->
                    <el-row>
                        <!-- <el-col :span="8">
                    <el-form-item label-width="120px" label="供应商:" prop="supplierId">
                        <el-select placeholder="---请选择供应商---" v-model="entityObj.supplierId" style="width: 60%;margin-right: 10px;" >
                            <el-option label="---请选择---" value />
                            <el-option v-for="item in entityObj.suppliers" :key="item.supplierId" :label="item.supplierName"
                                :value="item.supplierId" />
                        </el-select>
                        <el-button
                            size="small"
                            type="primary"
                            @click="opSendDetail()"
                        >发货明细</el-button>
                    </el-form-item>
                        </el-col>-->
                        <el-col :span="8">
                            <el-form-item label-width="120px" label="收货人:" prop="taskName">
                                <el-input v-model="entityObj.taskName" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label-width="120px" label="入库时间:" prop="inDate">
                                <el-input v-model="entityObj.inDate" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
            </el-collapse>
            <el-collapse class="title">
                <div class="collapse-header" @click="toggleCollapse1">
                    <span>发货信息</span>
                    <div style="display: flex;align-items: center;">
                        <span class="expand-text">{{ isCollapsed1 ? '展开' : '收起' }}</span>
                        <img
                            v-if="isCollapsed1"
                            class="icon-img"
                            src="https://oss.jtmckj.com/pc/images/pay/arrow-bt.png"
                        />
                        <img
                            v-else
                            class="icon-img"
                            src="https://oss.jtmckj.com/pc/images/pay/arrow-top.png"
                        />
                    </div>
                </div>
                <div v-show="!isCollapsed1" class="collapse-content1">
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label-width="80px" label="供应商:" prop="supplierId">
                                <el-tabs class="demo-tabs">
                                    <el-tab-pane
                                        v-for="(item,supplierIndex) in entityObj.suppliers"
                                        :key="item.supplierId"
                                    >
                                        <template #label>
                                            {{supplierIndex+1}}. {{item.supplierName}}
                                            <span
                                                style="color:red;font-size: 11px;"
                                                v-if="item.isDot"
                                            >(未填收货数量))</span>
                                        </template>
                                        <el-form inline label-width="49px">
                                            <el-form-item label label-width="80px">
                                                <el-button
                                                    size="small"
                                                    type="primary"
                                                    @click="opSendDetail(item.sendOrderItems)"
                                                >发货明细</el-button>
                                            </el-form-item>
                                            <el-form-item label="物料编号" label-width="80px">
                                                <el-input
                                                    placeholder="---请输入编号---"
                                                    v-model="queryList.materialCode"
                                                    style="width: 160px"
                                                />
                                            </el-form-item>
                                            <el-form-item label="物料名称" label-width="80px">
                                                <el-input
                                                    placeholder="---请输入名称---"
                                                    v-model="queryList.materialName"
                                                    style="width: 160px"
                                                />
                                            </el-form-item>
                                            <el-form-item label="物料分类" label-width="80px">
                                                <el-tree-select
                                                    v-model="queryList.materialTypeIds"
                                                    placeholder="---请选择物料分类---"
                                                    collapse-tags
                                                    collapse-tags-tooltip
                                                    :props="{ label: 'label', value: 'value', children: 'children' }"
                                                    :data="materialTypeTree"
                                                    multiple
                                                    :render-after-expand="false"
                                                    show-checkbox
                                                    style="width: 160px"
                                                />
                                            </el-form-item>
                                            <el-button
                                                :icon="Search"
                                                 
                                                type="primary"
                                                @click="handleSearch(item)"
                                            >查询</el-button>
                                            <el-button
                                                :icon="Search"
                                                type="info"
                                                plain
                                                @click="resetSearch"
                                            >重置</el-button>
                                            <el-form
                                                inline
                                                label-width="49px"
                                                style="margin-top: 5px"
                                            ></el-form>
                                        </el-form>
                                        <el-table
                                            :data="item.taskOrderItems"
                                            border
                                            show-summary
                                            :summary-method="getSummaries"
                                        >
                                            <!-- <el-table-column label="物料编码" width="110" prop="materialCode">
                                            </el-table-column>-->
                                            <el-table-column
                                                label="物料名称"
                                                width="150"
                                                prop="materialName"
                                            >
                                                <template #default="scope">
                                                    <el-tag
                                                        type="warning"
                                                        v-if="scope.row.orderType==9"
                                                    >待分配</el-tag>
                                                    {{scope.row.materialName}}
                                                </template>
                                            </el-table-column>
                                            <!-- <el-table-column label="分类" width="100" prop="materialTypeName">
                                            </el-table-column>-->
                                            <el-table-column
                                                label="规格"
                                                width="100"
                                                prop="materialSpecs"
                                            ></el-table-column>
                                            <el-table-column label="单位" width="70" prop="unitName"></el-table-column>
                                            <!-- <el-table-column label="采购/赠送" width="120" prop="taskOrderTypeDesc">
                                            </el-table-column>-->

                                            <el-table-column label="本次收货" min-width="120">
                                                <template #default="scope">
                                                    <el-input-number
                                                        v-model="scope.row.qty"
                                                        style="width: 100%;"
                                                        :precision="0"
                                                        :max="scope.row.pendingTaskQty"
                                                        :step="1"
                                                        :disabled="scope.row.pendingTaskQty==0"
                                                        controls-position="right"
                                                    ></el-input-number>
                                                </template>
                                            </el-table-column>
                                            <el-table-column label="要货" width="95" prop="applyQty"></el-table-column>
                                            <el-table-column
                                                label="预计收货"
                                                width="95"
                                                prop="deliveryQty"
                                            ></el-table-column>
                                            <el-table-column label="已收货" width="90" prop="taskQty"></el-table-column>
                                            <el-table-column
                                                label="未收货"
                                                width="90"
                                                prop="pendingTaskQty"
                                            ></el-table-column>
                                            <el-table-column label="已发货" width="90" prop="sendQty"></el-table-column>

                                            <!-- <el-table-column label="入库仓库"  prop="warehouseId" min-width="120"> 
                                        <template #default="scope">
                                            <el-select placeholder="---请选择出库仓库 ---" v-model="scope.row.warehouseId" :disabled="scope.row.pendingTaskQty==0"
                                                style="width: 100%">
                                                <el-option label="---请选择---" value /> 
                                                <el-option v-for="item in scope.row.warehouses" :key="item.warehouseId"
                                                    :label="item.warehouseName" :value="item.warehouseId" />
                                            </el-select>
                                        </template>
                                            </el-table-column>-->

                                            <el-table-column label="收货照片" width="120">
                                                <template #default="scope">
                                                    <el-image
                                                        v-for="(item,index) in scope.row.taskFiles"
                                                        :key="index"
                                                        style="width: 50px; height: 40px;margin: 4px;"
                                                        :src="item"
                                                        :zoom-rate="1.2"
                                                        :max-scale="7"
                                                        :min-scale="0.2"
                                                        :preview-src-list="[item]"
                                                        preview-teleported="true"
                                                        :z-index="9999"
                                                        fit="cover"
                                                    />
                                                </template>
                                            </el-table-column>
                                            <el-table-column label="操作" width="100">
                                                <template #default="scope">
                                                    <el-button
                                                        type="primary"
                                                        size="small"
                                                        @click="opPatch(scope.row)"
                                                    >上传</el-button>
                                                </template>
                                            </el-table-column>
                                        </el-table>
                                    </el-tab-pane>
                                </el-tabs>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
            </el-collapse>
        </el-form>
        <template #footer>
            <el-button @click="visible = false">取 消</el-button>
            <el-button
                v-if="mode != 'show'"
                type="primary"
                :loading="isSaveing"
                @click="isSaveing=true;submit()"
            >确认收货入库</el-button>
        </template>
    </full-screen-dialog>

    <send-detail-dialog
        v-if="dialogSendDetail"
        ref="sendDetailDialog"
        @fatherMethod="opBindData"
        @success="handleSaveSuccess"
        @closed="dialogSendDetail = false"
    ></send-detail-dialog>
    <task-files-dialog
        v-if="dialogTaskFiles"
        ref="taskFilesDialog"
        @setTaskFile="setTaskFile"
        @success="handleSaveSuccess"
        @closed="dialogTaskFiles = false"
    ></task-files-dialog>
</template>



<script>
import tool from "@/utils/tool";
import sendDetailDialog from "./sendDetail";
import taskFilesDialog from "./taskFiles";
export default {
    emits: ["success", "closed"],
    components: {
        sendDetailDialog,
        taskFilesDialog,
    },
    data() {
        return {
            mode: "Task",
            titleMap: {
                Send: "收货",
                Task: "收货",
            },
            entityObj: {
                orderDetail: [],
            },
            materialState: false,
            queryList: {},
            visible: false,
            isSaveing: false,
            needSaveFlag: false,
            dialogSendDetail: false,
            dialogTaskFiles: false,
            //验证规则
            rules: {
                taskName: [
                    { required: true, type: "string", message: "请填写" },
                ],
                inDate: [{ required: true, type: "string", message: "请填写" }],
                supplierId: [
                    { required: true, type: "number", message: "请填写" },
                ],
                logisticsCode: [
                    { required: true, type: "string", message: "请填写" },
                ],
            },
            props: {
                label: "supplierName",
                value: "supplierId",
            },
            materialProps: {
                label: "materialCode",
                value: "materialId",
                items: "materialItems",
            },
            materialTypeTree: [],
            optionsSuppliers: [],
            itemsData: [],
            currOpSupplierId: 0, //当前操作供应商ID
            isCollapsed: true,
            isCollapsed1: false,
        };
    },
    computed: {
        // itemsData() {
        //     let filtered = this.entityObj.purchaseProtocolItems;
        //     if (this.queryList.materialTypeIds&&this.queryList.materialTypeIds.length>0) {
        //         filtered = filtered.filter(item => {
        //             return this.queryList.materialTypeIds.includes(item.materialTypeId);
        //         });
        //     }
        //     if (this.queryList.materialCode) {
        //         filtered = filtered.filter(item => {
        //             return item.materialCode.includes(this.queryList.materialCode);
        //         });
        //     }
        //     if (this.queryList.materialName) {
        //         filtered = filtered.filter(item => {
        //             return item.materialName.includes(this.queryList.materialName);
        //         });
        //     }
        //     return filtered;
        // },
    },
    watch: {
        // 'entityObj.suppliers': {
        //     handler(newVal,oldVal) {
        //         newVal.map((supplier)=>{
        //             supplier.isDot=false;
        //             supplier.taskOrderItems.map((taskItem)=>{
        //                 if(parseInt(taskItem.qty) <=0)
        //                 {
        //                     supplier.isDot=true;
        //                 }
        //             });
        //             });
        //     },
        //     deep:true
        //}
    },
    methods: {
        //显示=
        open(mode = "Add") {
            this.mode = mode;
            this.visible = true;
            return this;
        },
        //发货明细
        opSendDetail(sendOrderItems) {
            if (!sendOrderItems || sendOrderItems.length == 0) {
                this.$message.error("无发货记录");
                return;
            }

            this.dialogSendDetail = true;
            this.$nextTick(() => {
                this.$refs.sendDetailDialog.setData(sendOrderItems);
                this.$refs.sendDetailDialog.open("Send");
            });
        },
        toggleCollapse() {
            this.isCollapsed = !this.isCollapsed; // 切换展开/收起状态
        },
        toggleCollapse1() {
            this.isCollapsed1 = !this.isCollapsed1; // 切换展开/收起状态
        },
        //表单提交方法
        submit() {
            var newTaskOrderItems = [];
            this.entityObj.suppliers.map((p) => {
                p.taskOrderItems.map((c) => {
                    newTaskOrderItems.push(c);
                });
            });
            console.log("newTaskOrderItems", newTaskOrderItems);
            this.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                    try {
                        var returnValue =
                            await this.$API.auth.PostProcessApi.post(
                                "task-order/batch-task",
                                {
                                    supplierId: this.entityObj.supplierId,
                                    storeId:
                                        this.entityObj.orderDetail[0].storeId,
                                    taskName: this.entityObj.taskName,
                                    inDate: this.entityObj.inDate,
                                    //taskFileStr:this.entityObj.taskFileStr,
                                    taskOrderItems: newTaskOrderItems,
                                }
                            );
                        if (returnValue.status == 200) {
                            this.$message.success("操作成功");
                            this.$emit("fatherMethod");
                            this.isSaveing = false;
                            this.visible = false;
                        } else {
                            this.$message.error("操作失败:" + returnValue.msg);
                            this.isSaveing = false;
                        }
                    } catch (error) {
                        this.loading = false;
                        this.isSaveing = false;
                        return false;
                    }
                }
            });
        },
        //表单注入数据
        async setData(data) {
            try {
                // var returnValue = await this.$API.auth.GetProcessApi.get(
                //     `task-order/pending-task/${data.taskOrderType}/${data.orderId}`,
                //     {}
                // );
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    `task-order/batch-pending-task`,
                    [...data]
                );
                if (returnValue.status == 200) {
                    this.entityObj = {
                        orderDetail: [...data],
                        ...returnValue.response,
                        inDate: tool.formatDate(new Date()),
                        taskName: tool.data.get("USER_INFO").Name,
                    };
                    console.log(this.entityObj);
                    this.queryList = {};
                    //this.handleSearch();
                    console.log("this.entityObj", this.entityObj);
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        async initOptions() {
            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "material-type/tree",
                    { status: 1 }
                );
                if (returnValue.status == 200) {
                    this.materialTypeTree = returnValue.response;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        handleSearch(item) {
            console.log("请求参数", this.queryList);
            this.itemsData = item.taskOrderItems;
            if (
                this.queryList.materialTypeIds &&
                this.queryList.materialTypeIds.length > 0
            ) {
                item.taskOrderItems = this.itemsData.filter((item) => {
                    return this.queryList.materialTypeIds.includes(
                        item.materialTypeId
                    );
                });
            }

            if (this.queryList.materialCode) {
                item.taskOrderItems = this.itemsData.filter((item) => {
                    return item.materialCode.includes(
                        this.queryList.materialCode
                    );
                });
            }

            if (this.queryList.materialName) {
                item.taskOrderItems = this.itemsData.filter((item) => {
                    return item.materialName.includes(
                        this.queryList.materialName
                    );
                });
            }
            console.log("查询结果", item.taskOrderItems);
        },

        formatDate(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, "0");
            const day = String(date.getDate()).padStart(2, "0");
            const hours = String(date.getHours()).padStart(2, "0");
            const minutes = String(date.getMinutes()).padStart(2, "0");
            const seconds = String(date.getSeconds()).padStart(2, "0");

            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        getSummaries(param) {
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = "合计";
                    return;
                }
                const values = data.map((item) =>
                    Number(item[column.property])
                );

                if (
                    column.property == "deliveryQty" ||
                    column.property == "taskQty"
                ) {
                    if (!values.every((item) => isNaN(item))) {
                        const total = values.reduce((a, b) => a + b, 0);
                        sums[index] = total;
                    }
                }
            });
            return sums;
        },
        //补录
        opPatch(row) {
            this.currOpSupplierId = row.supplierId;
            this.dialogTaskFiles = true;
            var data = {
                taskOrderId: 0,
                supplierId: row.supplierId,
                taskFiles: row.taskFiles,
            };
            this.$nextTick(() => {
                this.$refs.taskFilesDialog.open("Show").setData(data);
            });
        },
        setTaskFile(taskFiles) {
            var suppliers = this.entityObj.suppliers.filter(
                (p) => p.supplierId == this.currOpSupplierId
            );

            suppliers.map((supplier) => {
                supplier.taskOrderItems.map((taskItem) => {
                    taskItem.taskFiles = taskFiles.split(",");
                });
            });
        },
    },
    async mounted() {
        await this.initOptions();
    },
};
</script>

<style scoped>
.el-form-item {
    margin-bottom: 8px !important;
}

.collapse-container {
    border-top: 1px solid #f6f6f6;
    border-bottom: 1px solid #f6f6f6;
    padding: 10px 10px 10px 0;
    margin-bottom: 10px;
}

.collapse-header {
    display: flex;
    justify-content: space-between;
    cursor: pointer;
    padding: 10px;
    padding-left: 0;
    font-weight: bold;
    font-size: 16px;
}

.expand-text {
    color: #308bf2; /* Element UI 的蓝色 */
    font-size: 14px;
}
.icon-img {
    width: 16px;
    height: 10px;
    margin-left: 5px;
}
.collapse-content {
    padding: 10px;
}

.collapse-content1 {
    padding: 10px;
    background: #f2f2f2;
}
</style>
